package com.telit.common.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.telit.common.config.PushMessageProperties;
import com.telit.common.constant.ForestResultConstants;
import com.telit.common.exception.ForestBaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Auther amy
 * @Describe 阿里云发送短信方法
 */
@Service
@Slf4j
public class AliSmsService {

    @Autowired
    private PushMessageProperties pushMessageProperties;

    public void sendSms(String mobile, String params,String smsTemplate) throws ClientException {
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain(pushMessageProperties.getDomain());
            request.setVersion(pushMessageProperties.getVersion());
            request.setAction(pushMessageProperties.getAction());
            request.putQueryParameter("RegionId", pushMessageProperties.getRegionId());
            request.putQueryParameter("PhoneNumbers", mobile);
            request.putQueryParameter("SignName",pushMessageProperties.getSignName());

            //短信模板
            request.putQueryParameter("TemplateCode",smsTemplate);

            request.putQueryParameter("TemplateParam", params);

            DefaultProfile profile = DefaultProfile.getProfile(pushMessageProperties.getRegionId(), pushMessageProperties.getAccessKeyId(), pushMessageProperties.getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);

            CommonResponse response = client.getCommonResponse(request);
            JSONObject jsonObject = JSONObject.parseObject(response.getData());
            if (!"OK".equals(jsonObject.get("Code"))) {
                log.error("发送短信失败,Code:{},Message:{},mobile:{}", jsonObject.get("Code"), jsonObject.get("Message"), mobile);
                throw new ForestBaseException(ForestResultConstants.SMS_FAILED, jsonObject.get("Message").toString());
            }
    }
}
